package com.lframework.xingyun.basedata.impl.product;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.lframework.starter.common.exceptions.impl.DefaultClientException;
import com.lframework.starter.common.utils.Assert;
import com.lframework.starter.common.utils.ObjectUtil;
import com.lframework.starter.common.utils.StringUtil;
import com.lframework.starter.web.impl.BaseMpServiceImpl;
import com.lframework.starter.web.resp.PageResult;
import com.lframework.starter.web.utils.IdUtil;
import com.lframework.starter.web.utils.PageHelperUtil;
import com.lframework.starter.web.utils.PageResultUtil;
import com.lframework.xingyun.basedata.dto.product.UpdateProductDTO;
import com.lframework.xingyun.basedata.entity.Product;
import com.lframework.xingyun.basedata.entity.ProductSpu;
import com.lframework.xingyun.basedata.mappers.ProductSpuMapper;
import com.lframework.xingyun.basedata.service.product.ProductService;
import com.lframework.xingyun.basedata.service.product.ProductSpuService;
import com.lframework.xingyun.basedata.vo.product.info.CreateProductVo;
import com.lframework.xingyun.basedata.vo.product.spu.*;
import com.lframework.xingyun.template.core.annotations.OpLog;
import com.lframework.xingyun.template.core.enums.DefaultOpLogType;
import com.lframework.xingyun.template.core.utils.OpLogUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
public class ProductSpuServiceImpl extends BaseMpServiceImpl<ProductSpuMapper, ProductSpu> implements ProductSpuService {

    @Autowired
    private ProductService productService;

    @Override
    public PageResult<ProductSpu> query(Integer pageIndex, Integer pageSize, QueryProductSpuVo vo) {

        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        PageHelperUtil.startPage(pageIndex, pageSize);
        List<ProductSpu> datas = this.query(vo);

        return PageResultUtil.convert(new PageInfo<>(datas));
    }

    @Override
    public List<ProductSpu> query(QueryProductSpuVo vo) {

        return getBaseMapper().query(vo);
    }

    @Cacheable(value = ProductSpu.CACHE_NAME, key = "@cacheVariables.tenantId() + #id", unless = "#result == null")
    @Override
    public ProductSpu findById(String id) {

        return getBaseMapper().selectById(id);
    }

    @OpLog(type = DefaultOpLogType.OTHER, name = "新增商品SPU，ID：{}", params = {"#id"})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String create(CreateProductSpuVo vo) {
        // 验证商品编码
        Wrapper<ProductSpu> checkWrapper = Wrappers.lambdaQuery(ProductSpu.class)
        .eq(ProductSpu::getCode, vo.getCode());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
          throw new DefaultClientException("商品编码【"+vo.getCode()+"】重复，请重新输入！");
        }

        ProductSpu data = new ProductSpu();
        data.setId(IdUtil.getId());
        data.setCode(vo.getCode());
        data.setName(vo.getName());
        data.setShortName(vo.getShortName());
        data.setCategoryId(vo.getCategoryId());
        data.setBrandId(vo.getBrandId());
        data.setProductType(vo.getProductType());
        if (!StringUtil.isBlank(vo.getSpec())) {
            data.setSpec(vo.getSpec());
        }
        if (vo.getWeight() != null) {
            data.setWeight(vo.getWeight());
        }
        if (vo.getVolume() != null) {
            data.setVolume(vo.getVolume());
        }
        data.setAvailable(Boolean.TRUE);

        getBaseMapper().insert(data);

        OpLogUtil.setVariable("id", data.getId());
        OpLogUtil.setExtra(vo);

        for (CreateProductSpuItemVo sku : vo.getSkuItems()){
            CreateProductVo skuCreateVo = new CreateProductVo();
            BeanUtils.copyProperties(vo, skuCreateVo);
            BeanUtils.copyProperties(sku, skuCreateVo);
            skuCreateVo.setSpuId(data.getId());
            this.productService.create(skuCreateVo);
        }

        return data.getId();
    }

    @OpLog(type = DefaultOpLogType.OTHER, name = "修改商品SPU，ID：{}", params = {"#id"})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(UpdateProductSpuVo vo) {

        ProductSpu data = getBaseMapper().selectById(vo.getId());
        if (ObjectUtil.isNull(data)) {
            throw new DefaultClientException("商品SPU不存在！");
        }

        // 验证商品编码
        Wrapper<ProductSpu> checkWrapper = Wrappers.lambdaQuery(ProductSpu.class)
                .eq(ProductSpu::getCode, vo.getCode()).ne(ProductSpu::getId, data.getId());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
            throw new DefaultClientException("商品编码【"+vo.getCode()+"】重复，请重新输入！");
        }
        LambdaUpdateWrapper<ProductSpu> updateWrapper = Wrappers.lambdaUpdate(ProductSpu.class)
                .set(ProductSpu::getCode, vo.getCode())
                .set(ProductSpu::getName, vo.getName())
                .set(ProductSpu::getAvailable, vo.getAvailable())
                .set(ProductSpu::getShortName, vo.getShortName())
                .set(ProductSpu::getCategoryId, vo.getCategoryId())
                .set(ProductSpu::getBrandId, vo.getBrandId())
                .set(ProductSpu::getProductType, vo.getProductType())
                .set(ProductSpu::getSpec, StringUtil.isBlank(vo.getSpec()) ? null : vo.getSpec())
                .set(ProductSpu::getWeight, vo.getWeight() == null ? null : vo.getWeight())
                .set(ProductSpu::getVolume, vo.getVolume() == null ? null : vo.getVolume())
                .eq(ProductSpu::getId, vo.getId());

        getBaseMapper().update(updateWrapper);

        for (UpdateProductSpuItemVo sku : vo.getSkuItems()){
            UpdateProductDTO updateProductDTO = new UpdateProductDTO();
            BeanUtils.copyProperties(vo, updateProductDTO);
            BeanUtils.copyProperties(sku, updateProductDTO);
            // 商品SPU状态禁用后,其下所有SKU全部禁用
            if (!vo.getAvailable()){
                updateProductDTO.setAvailable(vo.getAvailable());
            }
            this.productService.update2(updateProductDTO);
        }

        OpLogUtil.setVariable("id", data.getId());
        OpLogUtil.setExtra(vo);
    }

    @CacheEvict(value = ProductSpu.CACHE_NAME, key = "@cacheVariables.tenantId() + #key")
    @Override
    public void cleanCacheByKey(Serializable key) {

    }
}
